import os.path
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.utils import formataddr
from email.header import Header as EmailHeader
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions

os.chdir(os.path.dirname(__file__))
print(os.path.abspath("ip.txt"))
# 发送邮件的相关信息
smtp_server = 'smtp.qq.com'  # 使用QQ邮箱的SMTP服务器地址
smtp_port = 587  # 使用QQ邮箱的SMTP服务器端口号
ip_file = open("ip.txt","r+")
ip = ip_file.read()



# sender = '3328650481@qq.com'  # 发件人邮箱
# password = 'mgukegxwuhsucjdh'  # 发件人邮箱的授权码
# receivers = ['1564024431@qq.com']  # 接收者邮箱地址，可以是列表（群发）或字符串（单发）

def sent_ip(sender='3328650481@qq.com', sender_authcode='mgukegxwuhsucjdh', receivers=None, subject="ip地址变化"):
    # 打开图片文件，并读取出图片内容
    if receivers is None:
        receivers = ['1564024431@qq.com']

    # 创建一封邮件
    message = MIMEMultipart()
    message['Subject'] = EmailHeader(subject, "utf-8").encode()
    message['From'] = formataddr((EmailHeader("冼铧城_laptop", "utf-8").encode(), sender))
    message['To'] = formataddr((EmailHeader("冼铧城_WeChat", "utf-8").encode(), receivers[0]))
    # 创建邮件正文
    text = MIMEText("新ip地址：\n" + ip, "plain", "utf-8")
    message.attach(text)

    # 发送邮件
    try:
        smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
        smtp_obj.ehlo()
        smtp_obj.starttls()  # 开启TLS加密
        smtp_obj.login(sender, sender_authcode)
        smtp_obj.sendmail(sender, receivers, message.as_string())
        print('邮件发送成功')
    except smtplib.SMTPException as e:
        print('邮件发送失败', e)


chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')

driver = webdriver.Chrome(options=chrome_options)

wait = WebDriverWait(driver, 20)
driver.get("http://172.29.0.1")
input_box = driver.find_element(By.NAME, "router_password")
input_box.send_keys("dabu8888")
button = driver.find_element(By.ID, "btnRtSubmit")
button.click()
wait.until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, "#nav ul li:nth-child(2)")))
tag = driver.find_element(By.CSS_SELECTOR, "#nav ul li:nth-child(2)")
tag.click()
wait.until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, ".ico.ico-2")))
driver.find_element(By.CSS_SELECTOR, ".ico.ico-2").click()
wait.until(expected_conditions.element_to_be_clickable(
    (By.CSS_SELECTOR, ".wanStatus ul li:nth-child(2) span:nth-child(2)")))
new_ip = driver.find_element(By.CSS_SELECTOR, ".wanStatus ul li:nth-child(2) span:nth-child(2)").text
print(new_ip)
if new_ip != ip:
    ip_file.seek(0,0)
    ip_file.truncate()
    ip_file.write(new_ip)
    sent_ip(subject="新ip地址： " + new_ip)
driver.quit()
